import subprocess
import re
import chardet
import webbrowser
import argparse  # 用于解析命令行参数

BASE_URL_1 = "http://172.25.249.64/eportal/index.jsp"  # 第一种情况
BASE_URL_2 = "http://10.253.0.213/srun_portal_pc?ac_id=1&theme=pro"  # 第二种情况
BASE_URL_3 = "http://221.10.255.233:8088"  # 第三种情况
NAS_IP = "171.88.130.251"

def run_command_with_encoding(command):
    """
    执行命令并自动检测编码，返回标准输出
    """
    try:
        result = subprocess.run(command, capture_output=True)
        encoding = chardet.detect(result.stdout)["encoding"]
        output = result.stdout.decode(encoding, errors="ignore")
        return output
    except Exception as e:
        print(f"命令执行失败: {e}")
        exit(1)

def get_ipv4_address():
    """
    获取无线局域网适配器 WLAN 的 IPv4 地址
    """
    try:
        output = run_command_with_encoding(["ipconfig"])
        match = re.search(r"无线局域网适配器 WLAN.*?IPv4 地址.*?:\s*([0-9\.]+)", output, re.S)
        if match:
            ipv4_address = match.group(1)
            print(f"IPv4 地址: {ipv4_address}")
            return ipv4_address
        else:
            raise ValueError("未找到 IPv4 地址！")
    except Exception as e:
        print(f"获取 IPv4 地址失败: {e}")
        exit(1)

def get_mac_address():
    """
    获取无线网络物理地址 (MAC)
    """
    try:
        output = run_command_with_encoding(["netsh", "wlan", "show", "interfaces"])
        mac_address_match = re.search(r"物理地址\s+:\s+([a-fA-F0-9:]+)", output)
        if mac_address_match:
            mac_address = mac_address_match.group(1)
            print(f"物理地址 (MAC): {mac_address}")
            return mac_address
        else:
            raise ValueError("未找到物理地址！")
    except Exception as e:
        print(f"获取物理地址失败: {e}")
        exit(1)

def open_authentication_page(user_ip, mac_address, base_url):
    """
    构建认证页面的 URL 并打开浏览器跳转
    """
    try:
        if "eportal" in base_url:  # 第一种情况需要附加参数
            params = {
                "userip": user_ip,
                "wlanacname": "",
                "nasip": NAS_IP,
                "wlanparameter": mac_address,
            }
            full_url = f"{base_url}?userip={params['userip']}&wlanacname={params['wlanacname']}&nasip={params['nasip']}&wlanparameter={params['wlanparameter']}"
        else:  # 第二/三种情况直接使用 base_url
            full_url = base_url

        print(f"完整 URL: {full_url}")

        # 使用默认浏览器打开认证页面
        webbrowser.open(full_url)
        print("已跳转到认证页面，请在浏览器中完成认证。")

    except Exception as e:
        print(f"跳转认证页面失败: {e}")

if __name__ == "__main__":
    # 设置命令行参数解析
    parser = argparse.ArgumentParser(description="跳转到网络认证页面")
    parser.add_argument(
        "--type",
        choices=["1", "2", "3"],
        required=True,
        help="认证类型：1 - 跳转到第一种情况的认证页面，2 - 跳转到第二种情况的认证页面",
    )
    args = parser.parse_args()

    # 获取命令行参数
    auth_type = args.type

    print("开始跳转到网络认证页面...")
    ipv4_address = get_ipv4_address()
    mac_address = get_mac_address()

    # 根据认证类型选择不同的 URL
    if auth_type == "1":
        open_authentication_page(ipv4_address, mac_address, BASE_URL_1)
    elif auth_type == "2":
        open_authentication_page(ipv4_address, mac_address, BASE_URL_2)
    elif auth_type == "3":
        open_authentication_page(ipv4_address, mac_address, BASE_URL_3)

